//
//  ClubGameForumView.swift
//  77Club
//
//  Created by Apple on 2024/11/4.
//

import UIKit
import VersaPlayer

class ClubGameForumTopView: UIView, RaeNetworkProtocol {
    
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(12.0.Scale).border(.white.alpha(0.1), width: 1)
        .mode(.scaleAspectFill).end()
    private let shadowView = c_make_ex(UIView.self)
        .bgColor(.black.alpha(0.1)).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color(.white).font(16.font_semiBold).end()
    private let joinLabel = c_make_ex(UILabel.self)
        .color(.white.alpha(0.8))
        .font(10.font_medium).end()
    private let timeLabel = c_make_ex(UILabel.self)
        .color(.white.alpha(0.8)).font(12.font_medium).end()
    private var joinButton = UIIconButton(style: .leading(itemSpace: 2))
    
    var communityId: String = ""
    var model: ClubGameCommunityModel? {
        didSet{
            guard let md = model else { return }
            
            iconImageView.loadImage(url: md.icon)
            nameLabel.text = md.name
            joinLabel.text = "\(md.guanzhu_num)" + "人已加入论坛"
            timeLabel.text = "最新更新：" + md.new_time
            joinButton.isSelected = md.shoucang_id.count > 0
        }
    }

    var joinBlock: ((_ isJoined: Bool, _ md: ClubGameCommunityModel) -> Void)?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
     
        clipsToBounds = true
        backgroundColor = .clear
        
        subviews{
            iconImageView.subviews{
                shadowView
            }
            nameLabel
            joinLabel
            timeLabel
            joinButton
        }
        
        shadowView.fillContainer()
        iconImageView.leading(12.0.Scale).size(80.0.Scale).top(8.0.Scale)
        nameLabel.leading(100.0.Scale).trailing(100.0.Scale).top(22.0.Scale)
        joinLabel.leading(100.0.Scale).trailing(100.0.Scale)
        joinLabel.Top == nameLabel.Bottom + 5
        timeLabel.leading(100.0.Scale).trailing(100.0.Scale)
        timeLabel.Top == joinLabel.Bottom + 5
        joinButton.trailing(12.0.Scale).width(80.0.Scale).height(30.0.Scale)
        joinButton.CenterY == iconImageView.CenterY
        
        joinButton.style { v in
            v.iconSize = CGSizeMake(12.0.Scale, 12.0.Scale)
            v.backgroundColor = .white.alpha(0.2)
            v.layer.cornerRadius = 15.0.Scale
            v.layer.masksToBounds = true
            v.setTitleColor(.white, for: .normal)
            v.setTitleColor("#AEB0B3".toColor, for: .selected)
            v.setImage("Square_detail_follow".toImage, for: .normal)
            v.setImage("Square_detail_followed".toImage, for: .selected)
            v.setTitle("关注", for: .normal)
            v.setTitle("已关注", for: .selected)
            v.titleLabel?.font = 14.font_medium
            v.addTarget(self, action: #selector(clickJoinButton), for: .touchUpInside)
        }

    }

    
    @objc private func clickJoinButton(){
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            ToastUtil.show()
            if joinButton.isSelected {
                Task{
                    let res = await network.request(.cancelCollectGoods(goodsId: model?.shoucang_id ?? "", type: "0"),isShowError: false)
                    if res.isSuccess {
                        joinButton.isSelected = false
                        "已取消关注".toast_success
                        // 使用正则表达式提取数字
                        let text = joinLabel.text ?? ""
                        joinLabel.text = ClubGlobalTool.shared.subtractionNumberInString(text: text)
                        let dict = ["isAttention": false]
                        DispatchQueue.main.async {
                            NotificationCenter.default.post(name: .updateGameInfoAttentionState, object: nil,userInfo: dict)
                        }
                    }
                }
            }else{
                Task{
                    let res = await network.request(.collectGoods(goodsId: communityId, type: "0"),isShowError: false)
                    if res.isSuccess {
                        joinButton.isSelected = true
                        "关注成功".toast_success
                        let text = joinLabel.text ?? ""
                        joinLabel.text = ClubGlobalTool.shared.calculateNumberInString(text: text)
                        let dict = ["isAttention": true]
                        DispatchQueue.main.async {
                            NotificationCenter.default.post(name: .updateGameInfoAttentionState, object: nil,userInfo: dict)
                        }
                    }
                }
            }
        }else{
            UIApplication.topController()?.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

//MARK: 分区titileView
class ClubGameForumHeaderView: UITableViewHeaderFooterView {
    
    private let nameLabel = c_make_ex(UILabel.self)
        .color("#323233").font(14.font_semiBold).end()
    private let sortButton = c_make_ex(UIButton.self)
        .image("GameDetail_sortNor").image("GameDetail_sortSel", state: .selected).end()
    
    var titleString: String? {
        didSet{
            guard let str = titleString else { return }
            nameLabel.text = str
        }
    }
    
    var updateDataBlock: ((_: String) -> Void)?
    
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        backgroundColor = .white
        contentView.backgroundColor = .white
        
        subviews{
            nameLabel
            sortButton
        }
        
        nameLabel.leading(12.0.Scale).centerVertically()
        sortButton.trailing(12.0.Scale).width(76.0.Scale).height(28.0.Scale).centerVertically()

        sortButton.addTarget(self, action: #selector(clickSortButton), for: .touchUpInside)
    }
    
    @objc private func clickSortButton(){
        
        sortButton.isSelected = !sortButton.isSelected
        let sortType = sortButton.isSelected ? "0" : "1"
        updateDataBlock?(sortType)
    }
        
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    
}



class ClubGameForumCell: UITableViewCell, RaeNetworkProtocol {
    
    private let backView = c_make_ex(UIView.self)
        .bgColor("#F7F8FA").corner(12.0.Scale).end()
    private let iconImageView = c_make_ex(UIImageView.self)
        .corner(20.0.Scale).mode(.scaleAspectFill).end()
    private let nameLabel = c_make_ex(UILabel.self)
        .color(.black).font(12.font_semiBold).end()
    private let timeLabel = c_make_ex(UILabel.self)
        .color("#AEB0B3").font(11.font_medium).end()
    private let titleLabel = c_make_ex(UILabel.self)
        .color("#47494D").font(16.font_semiBold).end()
    private let contentLabel = c_make_ex(UILabel.self)
        .color("#47494D").font(15.font_regular)
        .line(0).end()
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    private let browseImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).image("Square_look").end()
    private let commitImageView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).image("Square_commit").end()
    private let likeImageView = c_make_ex(UIButton.self)
        .image("Square_like").image("Square_liked", state: .selected).end()
    private let browseLabel = c_make_ex(UILabel.self)
        .color("#7B7D80").font(11.font_regular).text("999浏览").end()
    private let commitLikeLabel = c_make_ex(UILabel.self)
        .color("#7B7D80").font(11.font_regular).alignment(.right).end()
    private lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 2.0.Scale
        layout.minimumInteritemSpacing = 2.0.Scale
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets(top: 0, left: 64.0.Scale, bottom: 0, right: 15.0.Scale)
        layout.itemSize = CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
        return layout
    }()
    private var showCount = 0
    
    var model: ClubGameCommunityListModel?{
        didSet{
            guard let md = model else { return }

            iconImageView.loadImage(url: md.face)
            nameLabel.text = md.fabu
            titleLabel.text = md.title
            contentLabel.text = md.content
            timeLabel.text = ClubGlobalTool.shared.timeDescription(from: md.time)
            if md.look == "0" {
                browseLabel.text = "浏览"
            }else{
                browseLabel.text = md.look + "浏览"
            }
            var pinglun = md.pinglun
            if pinglun == "0"{
                pinglun = ""
            }
            var good = md.good
            if good == "0"{
                good = ""
            }
            commitLikeLabel.text = pinglun + "评论 · " + good + "点赞"
            likeImageView.isSelected = md.is_good
            
            var itemSize: CGSize = .zero
            if md.video.count > 0 {
                itemSize = CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
                collectionView.heightConstraint?.constant = 152.0.Scale
                self.showCount = 1
            }else if md.image.count == 1 {
                itemSize = CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
                collectionView.heightConstraint?.constant = 152.0.Scale
                self.showCount = 1
            }else if md.image.count == 2 {
                itemSize = CGSize (width: (CGFloat.screenWidth - 106.0.Scale)/2.0, height: 83.0.Scale)
                collectionView.heightConstraint?.constant = 85.0.Scale
                self.showCount = 2
            }else if md.image.count > 2 {
                let w = (CGFloat.screenWidth - 110.0.Scale)/3
                itemSize = CGSize (width: w, height: w)
                if md.image.count == 3 || md.image.count == 4 || md.image.count == 5 {
                    collectionView.heightConstraint?.constant = w
                    self.showCount = 3
                }else if md.image.count == 6 || md.image.count == 7 || md.image.count == 8 {
                    collectionView.heightConstraint?.constant = w * 2 + 2
                    self.showCount = 6
                }else{
                    collectionView.heightConstraint?.constant = w * 3 + 4
                    self.showCount = 9
                }
            }else{
                collectionView.heightConstraint?.constant = 0
            }
            layout.itemSize = itemSize
            collectionView.collectionViewLayout = layout
            collectionView.reloadData()
        }
    }
    
//    var zanButtonClick:((_:String)->())?
    var likeBlock:(()->())?
    var jumpToDetail:((_:String,_ uid: String)->())?
    /// 点击图片
    var didSelectImage:((_:Int,_:[String])->())?
    /// 点击视频
    var didSelectVideo:((_:String)->())?
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        selectionStyle = .none
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        contentView.subviews{
            backView.subviews{
                iconImageView
                nameLabel
                timeLabel
                titleLabel
                contentLabel
                collectionView
                browseImageView
                commitImageView
                likeImageView
                browseLabel
                commitLikeLabel
            }
        }
        
        backView.leading(12.0.Scale).trailing(12.0.Scale).top(12.0.Scale).bottom(0)
        iconImageView.leading(12.0.Scale).top(16.0.Scale).size(40.0.Scale)
        nameLabel.leading(64.0.Scale).top(20.0.Scale).trailing(65.0.Scale)
        timeLabel.leading(64.0.Scale).top(40.0.Scale).trailing(65.0.Scale)
        titleLabel.leading(64.0.Scale).top(64.0.Scale).trailing(16.0.Scale)
        contentLabel.leading(64.0.Scale).top(88.0.Scale).trailing(16.0.Scale)
        collectionView.leading(0).trailing(0).height(0)
        collectionView.Top == contentLabel.Bottom + 8.0.Scale
        browseImageView.leading(52.0.Scale).size(44.0.Scale)
        browseImageView.Top == collectionView.Bottom
        likeImageView.trailing(4.0.Scale).size(44.0.Scale)
        likeImageView.CenterY == browseImageView.CenterY
        commitImageView.size(44.0.Scale)
        commitImageView.CenterY == likeImageView.CenterY
        commitImageView.Trailing == likeImageView.Leading
        browseLabel.leading(64.0.Scale).bottom(15.0.Scale)
        browseLabel.Top == browseImageView.Bottom
        commitLikeLabel.trailing(16.0.Scale)
        commitLikeLabel.CenterY == browseLabel.CenterY
        
//        let layout = UICollectionViewFlowLayout()
//        layout.minimumLineSpacing = 2.0.Scale
//        layout.minimumInteritemSpacing = 2.0.Scale
//        layout.scrollDirection = .vertical
//        layout.sectionInset = UIEdgeInsets(top: 0, left: 64.0.Scale, bottom: 0, right: 15.0.Scale)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(ClubGameCircleCell.self, forCellWithReuseIdentifier: ClubGameCircleCell.description())
        collectionView.showsVerticalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
                
        let tapG = UITapGestureRecognizer.init(target: self, action: #selector(commentButtonClick))
        commitImageView.isUserInteractionEnabled = true
        commitImageView.addGestureRecognizer(tapG)
        likeImageView.addTarget(self, action: #selector(likeButtonClick), for: .touchUpInside)
    }
    
    @objc private func commentButtonClick() {
        jumpToDetail?(model?.id ?? "", model?.uid ?? "")
    }
    
    @objc private func likeButtonClick(){
//        zanButtonClick?()
        guard let md = model else { return }
        let postId = md.id
        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            Task{
                ToastUtil.show()
                let _ = await self.network.request(.likeStrategyPost(pid: postId, puid: "", type: "0"))
                ToastUtil.dismiss()
                "点赞成功".toast_success
                likeImageView.isSelected = !likeImageView.isSelected
                let strArray = commitLikeLabel.text!.components(separatedBy: " · ")
                var zanString = strArray.last ?? ""
                if zanString == "点赞" {
                    zanString = "1点赞"
                }else{
                    if likeImageView.isSelected {
                        zanString = ClubGlobalTool.shared.calculateNumberInString(text: zanString)
                    }else{
                        zanString = ClubGlobalTool.shared.subtractionNumberInString(text: zanString)
                        if zanString == "0点赞"{
                            zanString = "点赞"
                        }
                    }
                }                
                var pinglun = md.pinglun
                if pinglun == "0"{
                    pinglun = ""
                }
                commitLikeLabel.text = pinglun + "评论 · " + zanString
                likeBlock?()
            }
        }else{
            UIApplication.topController()?.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
}

extension ClubGameForumCell: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if model?.video.count ?? 0 > 0 {
            return 1
        }else{
            return self.showCount
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let pageCell = collectionView.dequeueReusableCell(withReuseIdentifier: ClubGameCircleCell.description(), for: indexPath) as? ClubGameCircleCell else { return UICollectionViewCell() }
        pageCell.forumModel = model
        if model?.video.count ?? 0 > 0{
            
        }else{
            
            pageCell.imageView.loadImage(url: model?.image[indexPath.row])
        }
        pageCell.layoutIfNeeded()
        let count = model?.image.count ?? 0
        pageCell.isHiddenMore = true
        if self.showCount == 1 {
            pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 8.0.Scale)
        }else if self.showCount == 2 {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft], radius: 8.0.Scale)
            }else {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }else if self.showCount == 3 {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft], radius: 8.0.Scale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight,.bottomRight], radius: 8.0.Scale)
            }else {
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
            if count - self.showCount > 0 && indexPath.row == 2 {
                pageCell.isHiddenMore = false
                pageCell.moreLabel.setTitle("+\(count - self.showCount)", for: .normal)
            }else{
                pageCell.isHiddenMore = true
            }
        }else if self.showCount == 6 {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8.0.Scale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight], radius: 8.0.Scale)
            }else if indexPath.row == 3 {
                pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8.0.Scale)
            }else if indexPath.row == 5 {
                pageCell.imageView.addCorner(conrners: [.bottomRight], radius: 8.0.Scale)
            }else{
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
            if count - self.showCount > 0 && indexPath.row == 5 {
                pageCell.isHiddenMore = false
                pageCell.moreLabel.setTitle("+\(count - self.showCount)", for: .normal)
            }else{
                pageCell.isHiddenMore = true
            }
        }else {
            if indexPath.row == 0 {
                pageCell.imageView.addCorner(conrners: [.topLeft], radius: 8.0.Scale)
            }else if indexPath.row == 2{
                pageCell.imageView.addCorner(conrners: [.topRight], radius: 8.0.Scale)
            }else if indexPath.row == 6 {
                pageCell.imageView.addCorner(conrners: [.bottomLeft], radius: 8.0.Scale)
            }else if indexPath.row == 8 {
                pageCell.imageView.addCorner(conrners: [.bottomRight], radius: 8.0.Scale)
            }else{
                pageCell.imageView.addCorner(conrners: [.topLeft,.bottomLeft,.topRight,.bottomRight], radius: 0)
            }
        }
        
        return pageCell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if model?.video.count ?? 0 > 0 {
            didSelectVideo?((model?.video)!)
        }else{
            didSelectImage?(indexPath.row,model?.image ?? [])
        }
    }
}
